package com.example.teacherservice.controller;

import com.example.teacherservice.dto.BatchCartRequestDTO;
import com.example.teacherservice.dto.CartOrderDTO;
import com.example.teacherservice.dto.CartRequestDTO;
import com.example.teacherservice.dto.BatchOrderDTO;
import com.example.teacherservice.entity.Course;
import com.example.teacherservice.entity.StuCou;
import com.example.teacherservice.entity.StuOrder;
import com.example.teacherservice.repository.CourseRepository;
import com.example.teacherservice.repository.StuCouRepository;
import com.example.teacherservice.repository.StuOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private StuOrderRepository orderRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StuCouRepository stuCouRepository;

    // 单个课程添加到购物车
    @PostMapping("/add-course/{courseId}")
    public ResponseEntity<?> addCourseToCart(
            @PathVariable Long courseId,
            @RequestBody CartRequestDTO request) {
        try {
            // 1. 检查课程是否存在
            if (!courseRepository.existsById(courseId)) {
                throw new RuntimeException("课程不存在");
            }

            // 2. 检查是否已在购物车
            if (stuCouRepository.existsByStuIdAndCouId(request.getStudentId(), courseId)) {
                throw new RuntimeException("该课程已在购物车中");
            }

            // 3. 创建并保存stu_cou记录
            StuCou stuCou = new StuCou();
            stuCou.setStuId(request.getStudentId());
            stuCou.setCouId(courseId);
            stuCou.setCouType(0); // 默认类型
            stuCouRepository.save(stuCou);

            return ResponseEntity.ok().body("课程已成功添加到购物车");

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误，请稍后再试");
        }
    }

    // 批量添加课程到购物车
    @PostMapping("/batch-add-courses")
    public ResponseEntity<?> batchAddCoursesToCart(
            @RequestBody BatchCartRequestDTO request) {
        try {
            // 参数校验
            if (request.getStudentId() == null) {
                throw new RuntimeException("学生ID不能为空");
            }
            if (request.getCourseIds() == null || request.getCourseIds().isEmpty()) {
                throw new RuntimeException("课程ID列表不能为空");
            }

            // 1. 检查所有课程是否存在
            List<Course> existingCourses = courseRepository.findAllById(request.getCourseIds());
            if (existingCourses.size() != request.getCourseIds().size()) {
                List<Long> missingIds = request.getCourseIds().stream()
                        .filter(id -> existingCourses.stream().noneMatch(c -> c.getId().equals(id)))
                        .collect(Collectors.toList());
                throw new RuntimeException("以下课程不存在: " + missingIds);
            }

            // 2. 过滤掉已存在的课程
            List<StuCou> existingCartItems = stuCouRepository.findByStuIdAndCouIdIn(
                    request.getStudentId(), request.getCourseIds());

            Set<Long> existingCourseIds = existingCartItems.stream()
                    .map(StuCou::getCouId)
                    .collect(Collectors.toSet());

            List<StuCou> newCartItems = request.getCourseIds().stream()
                    .filter(id -> !existingCourseIds.contains(id))
                    .map(id -> {
                        StuCou item = new StuCou();
                        item.setStuId(request.getStudentId());
                        item.setCouId(id);
                        item.setCouType(0);
                        return item;
                    })
                    .collect(Collectors.toList());

            // 3. 批量保存
            if (!newCartItems.isEmpty()) {
                stuCouRepository.saveAll(newCartItems);
                return ResponseEntity.ok().body(Map.of(
                        "success", true,
                        "message", "成功添加" + newCartItems.size() + "门课程到购物车",
                        "addedCourses", newCartItems.stream().map(StuCou::getCouId).collect(Collectors.toList())
                ));
            } else {
                return ResponseEntity.ok().body(Map.of(
                        "success", true,
                        "message", "所有课程已在购物车中",
                        "existingCourses", existingCourseIds
                ));
            }

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "系统错误: " + e.getMessage()
            ));
        }
    }

    // 创建订单并从购物车移除课程
    @PostMapping("/create-order/{courseId}")
    public ResponseEntity<?> createOrderAndRemoveFromCart(
            @PathVariable Long courseId,
            @RequestBody CartRequestDTO request) {
        try {
            // 1. 检查课程是否存在
            Course course = courseRepository.findById(courseId)
                    .orElseThrow(() -> new RuntimeException("课程不存在"));

            // 2. 生成订单
            StuOrder order = createOrder(request.getStudentId(), course.getCouPrice());

            // 3. 从购物车移除该课程
            stuCouRepository.deleteByStuIdAndCouId(request.getStudentId(), courseId);

            return ResponseEntity.ok(convertToOrderDTO(order));

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误，请稍后再试");
        }
    }

    // 从购物车批量移除课程
    @DeleteMapping("/batch-remove-courses")
    public ResponseEntity<?> batchRemoveCoursesFromCart(
            @RequestBody BatchCartRequestDTO request) {
        try {
            // 参数校验
            if (request.getStudentId() == null) {
                throw new RuntimeException("学生ID不能为空");
            }
            if (request.getCourseIds() == null || request.getCourseIds().isEmpty()) {
                throw new RuntimeException("课程ID列表不能为空");
            }

            // 1. 检查所有课程是否在购物车中
            List<StuCou> existingItems = stuCouRepository.findByStuIdAndCouIdIn(
                    request.getStudentId(), request.getCourseIds());

            // 2. 验证是否所有课程都在购物车中
            Set<Long> existingCourseIds = existingItems.stream()
                    .map(StuCou::getCouId)
                    .collect(Collectors.toSet());

            List<Long> missingCourses = request.getCourseIds().stream()
                    .filter(id -> !existingCourseIds.contains(id))
                    .collect(Collectors.toList());

            if (!missingCourses.isEmpty()) {
                throw new RuntimeException("以下课程不在购物车中: " + missingCourses);
            }

            // 3. 批量删除（使用更高效的删除方式）
            stuCouRepository.deleteByStuIdAndCouIdIn(
                    request.getStudentId(), request.getCourseIds());

            return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "成功移除" + existingItems.size() + "门课程",
                    "removedCourses", request.getCourseIds()
            ));

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", e.getMessage()
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "系统错误: " + e.getMessage()
            ));
        }
    }

    // 检查课程是否在购物车中
    @GetMapping("/check-course/{courseId}")
    public ResponseEntity<?> checkCourseInCart(
            @PathVariable Long courseId,
            @RequestParam Long studentId) {
        try {
            boolean inCart = stuCouRepository.existsByStuIdAndCouId(studentId, courseId);
            return ResponseEntity.ok().body(Map.of("inCart", inCart));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("检查购物车状态失败");
        }
    }

    // 从购物车移除单个课程
    @DeleteMapping("/remove-course/{courseId}")
    public ResponseEntity<?> removeCourseFromCart(
            @PathVariable Long courseId,
            @RequestParam Long studentId) {
        try {
            stuCouRepository.deleteByStuIdAndCouId(studentId, courseId);
            return ResponseEntity.ok().body("课程已从购物车移除");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("移除课程失败");
        }
    }

    // 获取学生购物车中的课程列表
    @GetMapping("/student-courses")
    public ResponseEntity<?> getStudentCartCourses(
            @RequestParam Long studentId) {
        try {
            // 1. 获取购物车中的课程ID列表
            List<Long> courseIds = stuCouRepository.findCourseIdsByStudentId(studentId);

            // 2. 根据课程ID列表查询课程基本信息
            List<Map<String, Object>> courses = courseRepository.findCourseBasicInfoByIds(courseIds);

            return ResponseEntity.ok().body(courses);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("获取购物车课程失败");
        }
    }

    // 创建订单的公共方法
    private StuOrder createOrder(Long studentId, double amount) {
        String orderCode = "ORD" + System.currentTimeMillis() +
                UUID.randomUUID().toString().substring(0, 6);

        StuOrder order = new StuOrder();
        order.setCode(orderCode);
        order.setStuId(studentId);
        order.setAmount((long) amount);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setDeleted(0);

        return orderRepository.save(order);
    }

    // 转换订单为DTO的公共方法
    private CartOrderDTO convertToOrderDTO(StuOrder order) {
        return CartOrderDTO.builder()
                .id(order.getId())
                .orderCode(order.getCode())
                .studentId(order.getStuId())
                .amount(order.getAmount())
                .createTime(order.getCreateTime())
                .build();
    }

    @PostMapping("/batch-create-orders")
    public ResponseEntity<?> batchCreateOrders(
            @RequestBody BatchOrderDTO request) {
        try {
            // 1. 检查所有课程是否存在
            List<Course> courses = courseRepository.findAllById(request.getCourseIds());
            if (courses.size() != request.getCourseIds().size()) {
                throw new RuntimeException("部分课程不存在");
            }

            // 2. 计算总金额
            double totalAmount = courses.stream()
                    .mapToDouble(Course::getCouPrice)
                    .sum();

            // 3. 创建订单
            StuOrder order = createOrder(request.getStudentId(), totalAmount);

            // 4. 返回订单信息（不再从购物车删除课程）
            return ResponseEntity.ok(convertToOrderDTO(order));

        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统错误，请稍后再试");
        }
    }
}